import { Component, PropsWithChildren } from 'react'
import { View, Text, Image, ScrollView, Input, Picker } from '@tarojs/components'
interface CustomScrollViewProps {
  onPullDownRefresh?: () => void
  refreshing?: boolean
}
import { 
  AtButton, 
  AtCard, 
  AtTag, 
  AtInput, 
  AtFloatLayout, 
  AtIcon,
  AtProgress,
  AtBadge,
  AtSearchBar,
  AtActionSheet,
  AtActionSheetItem
} from 'taro-ui'
import 'taro-ui/dist/style/components/float-layout.scss'
import 'taro-ui/dist/style/components/input.scss'
import 'taro-ui/dist/style/components/button.scss'
import 'taro-ui/dist/style/components/search-bar.scss'
import 'taro-ui/dist/style/components/action-sheet.scss'
import Taro from '@tarojs/taro'
import './index.scss'
import { getFoodList, saveFoodList, addFood, calculateStatus, exportFoodData, importFoodData, updateFood, deleteFood, deleteAllFood, checkFoodExists, addCustomFood, getCustomFoods } from '../../services/foodService'

interface FoodItem {
  id: string
  name: string
  category: string
  quantity: number
  unit: string
  purchaseDate: string
  expiryDate: string
  status: 'normal' | 'low' | 'expiring'
  location?: string
  image?: string
}

interface State {
  foodList: FoodItem[]
  showAddModal: boolean
  newFood: Partial<Omit<FoodItem, 'id' | 'purchaseDate' | 'status'>>
  refreshing: boolean
  showFoodSelector: boolean
  showCategorySelector: boolean
  showUnitSelector: boolean
  showLocationSelector: boolean
  foodSearchValue: string
  categorySearchValue: string
  // 新增筛选和排序状态
  selectedCategory: string
  selectedLocation: string
  sortBy: string
  showCategoryFilter: boolean
  showLocationFilter: boolean
  showSortFilter: boolean
  // 新增输入框焦点状态
  quantityInputFocused: boolean
  nameInputFocused: boolean
  // 新增搜索功能状态
  showSearchModal: boolean
  searchQuery: string
  searchResults: FoodItem[]
  // 新增总食材模态框状态
  showTotalIngredientsModal: boolean
  // 新增需关注模态框状态
  showAttentionModal: boolean
  // 新增编辑功能状态
  showEditModal: boolean
  editingFood: FoodItem | null
  editFood: Partial<FoodItem>
  // 编辑模态框的选择器状态
  showEditFoodSelector: boolean
  showEditCategorySelector: boolean
  showEditUnitSelector: boolean
  showEditLocationSelector: boolean
  editFoodSearchValue: string
  editCategorySearchValue: string
  // 新增用户指南状态
  showUserGuide: boolean
  userGuideClosing: boolean
}

export default class Kitchen extends Component<PropsWithChildren, State> {
  // 预置食材数据
  private presetFoods = [
    // 蔬菜类
    { name: '西红柿', category: '蔬菜', emoji: '🍅' },
    { name: '黄瓜', category: '蔬菜', emoji: '🥒' },
    { name: '胡萝卜', category: '蔬菜', emoji: '🥕' },
    { name: '白菜', category: '蔬菜', emoji: '🥬' },
    { name: '菠菜', category: '蔬菜', emoji: '🥬' },
    { name: '土豆', category: '蔬菜', emoji: '🥔' },
    { name: '洋葱', category: '蔬菜', emoji: '🧅' },
    { name: '青椒', category: '蔬菜', emoji: '🫑' },
    { name: '茄子', category: '蔬菜', emoji: '🍆' },
    { name: '韭菜', category: '蔬菜', emoji: '🥬' },
    
    // 水果类
    { name: '苹果', category: '水果', emoji: '🍎' },
    { name: '香蕉', category: '水果', emoji: '🍌' },
    { name: '橙子', category: '水果', emoji: '🍊' },
    { name: '葡萄', category: '水果', emoji: '🍇' },
    { name: '草莓', category: '水果', emoji: '🍓' },
    { name: '西瓜', category: '水果', emoji: '🍉' },
    { name: '桃子', category: '水果', emoji: '🍑' },
    { name: '梨', category: '水果', emoji: '🍐' },
    
    // 肉类
    { name: '猪肉', category: '肉类', emoji: '🥩' },
    { name: '牛肉', category: '肉类', emoji: '🥩' },
    { name: '鸡肉', category: '肉类', emoji: '🍗' },
    { name: '鸭肉', category: '肉类', emoji: '🦆' },
    { name: '鱼肉', category: '肉类', emoji: '🐟' },
    { name: '虾', category: '肉类', emoji: '🦐' },
    { name: '蟹', category: '肉类', emoji: '🦀' },
    
    // 主食类
    { name: '大米', category: '主食', emoji: '🍚' },
    { name: '面条', category: '主食', emoji: '🍜' },
    { name: '面包', category: '主食', emoji: '🍞' },
    { name: '馒头', category: '主食', emoji: '🥟' },
    { name: '饺子', category: '主食', emoji: '🥟' },
    
    // 调料类
    { name: '盐', category: '调料', emoji: '🧂' },
    { name: '糖', category: '调料', emoji: '🍯' },
    { name: '醋', category: '调料', emoji: '🍶' },
    { name: '酱油', category: '调料', emoji: '🍶' },
    { name: '料酒', category: '调料', emoji: '🍶' },
    { name: '胡椒粉', category: '调料', emoji: '🧂' },
    
    // 蛋奶类
    { name: '鸡蛋', category: '蛋奶', emoji: '🥚' },
    { name: '牛奶', category: '蛋奶', emoji: '🥛' },
    { name: '酸奶', category: '蛋奶', emoji: '🥛' },
    { name: '奶酪', category: '蛋奶', emoji: '🧀' }
  ]

  // 预置分类
  private presetCategories = [
    { name: '蔬菜', emoji: '🥬' },
    { name: '水果', emoji: '🍎' },
    { name: '肉类', emoji: '🥩' },
    { name: '主食', emoji: '🍚' },
    { name: '调料', emoji: '🧂' },
    { name: '蛋奶', emoji: '🥚' },
    { name: '其他', emoji: '🍱' }
  ]

  // 预置单位
  private presetUnits = [
    '个', '只', '条', '根', '片', '块', '颗', '粒',
    'kg', 'g', '斤', '两', '克', '千克',
    'L', 'ml', '升', '毫升', '瓶', '罐', '包', '袋', '盒'
  ]

  // 预置存放位置
  private presetLocations = [
    { name: '冷藏一层', emoji: '❄️' },
    { name: '冷藏二层', emoji: '❄️' },
    { name: '冷藏三层', emoji: '❄️' },
    { name: '冷冻', emoji: '🧊' },
    {name: '客厅五斗柜', emoji: '⚱️' },
    {name: '客厅置物柜', emoji: '⚱️' },
    {name: '小房间', emoji: '⚱️' },
    {name: '其他', emoji: '😋' },
  ]

  constructor(props: PropsWithChildren) {
    super(props)
    this.state = {
      foodList: [],
      showAddModal: false,
      newFood: {},
      refreshing: false,
      showFoodSelector: false,
      showCategorySelector: false,
      showUnitSelector: false,
      showLocationSelector: false,
      foodSearchValue: '',
      categorySearchValue: '',
      // 新增筛选和排序状态初始值
      selectedCategory: '分类排序',
      selectedLocation: '位置排序',
      sortBy: '按名称排序',
      showCategoryFilter: false,
      showLocationFilter: false,
      showSortFilter: false,
      // 新增输入框焦点状态初始值
      quantityInputFocused: false,
      nameInputFocused: false,
      // 新增搜索功能状态初始值
      showSearchModal: false,
      searchQuery: '',
      searchResults: [],
  // 新增总食材模态框状态初始值
  showTotalIngredientsModal: false,
  // 新增需关注模态框状态初始值
  showAttentionModal: false,
      // 新增编辑功能状态初始值
      showEditModal: false,
      editingFood: null,
      editFood: {},
      // 编辑模态框的选择器状态初始值
      showEditFoodSelector: false,
      showEditCategorySelector: false,
      showEditUnitSelector: false,
      showEditLocationSelector: false,
      editFoodSearchValue: '',
      editCategorySearchValue: '',
      // 新增用户指南状态初始值
      showUserGuide: true,
      userGuideClosing: false
    }
  }

  componentDidMount() {
    // 组件挂载后从本地存储加载数据
    const savedFoodList = getFoodList();
    // 更新状态，确保状态是最新的
    this.setState({ foodList: savedFoodList });
    
    // 检查是否是首次访问，决定是否显示用户指南
    this.checkFirstVisit();
  }

  // 检查是否是首次访问
  checkFirstVisit = () => {
    try {
      const hasVisited = Taro.getStorageSync('kitchen_has_visited');
      if (!hasVisited) {
        // 首次访问，显示用户指南
        this.setState({ showUserGuide: true });
        // 标记已访问
        Taro.setStorageSync('kitchen_has_visited', true);
      } else {
        // 非首次访问，不显示用户指南
        this.setState({ showUserGuide: false });
      }
    } catch (error) {
      console.error('检查首次访问状态失败:', error);
      // 出错时默认不显示用户指南
      this.setState({ showUserGuide: false });
    }
  }

  // 关闭用户指南
  handleCloseUserGuide = () => {
    // 立即关闭，无延时
    this.setState({ showUserGuide: false });
  }

  // 显示用户指南
  handleShowUserGuide = () => {
    this.setState({ showUserGuide: true });
  }

  handleAddFood = () => {
    this.setState({ showAddModal: true })
  }

  handleCloseModal = () => {
    this.setState({ showAddModal: false, newFood: {} })
  }

  handleSaveFood = () => {
    const { newFood, foodList } = this.state
    
    // Check for required fields: name and quantity
    if (!newFood.name || !newFood.quantity) {
      Taro.showToast({ title: '请填写食材名称和数量', icon: 'none' })
      return
    }

    // 检查食材是否已存在
    if (checkFoodExists(newFood.name)) {
      Taro.showToast({ 
        title: `食材"${newFood.name}"已存在，请勿重复添加`, 
        icon: 'none',
        duration: 3000
      })
      return
    }

    // 确保 newFood 的类型符合要求，处理可能的 undefined
    // 不设置默认值，只有用户选择了才设置
    const validNewFood: Omit<FoodItem, 'id' | 'purchaseDate' | 'status'> = {
      name: newFood.name ?? '',
      category: newFood.category ?? '', // 不设置默认分类
      quantity: newFood.quantity ?? 0,
      unit: newFood.unit ?? '', // Keep empty if not selected
      expiryDate: newFood.expiryDate ?? '', // Keep empty if not selected
      location: newFood.location ?? '' // Keep empty if not selected
    };

    // 如果是新的食材名称且有分类，添加到自定义食材列表
    if (validNewFood.name && validNewFood.category) {
      const result = addCustomFood(validNewFood.name, validNewFood.category);
      if (!result.success) {
        console.log('添加自定义食材信息:', result.message);
      }
    }

    // 使用服务层创建新食材
    const newItem = addFood(validNewFood);

    // 更新状态
    const updatedList = [...foodList, newItem];
    this.setState({
      foodList: updatedList,
      showAddModal: false,
      newFood: {}
    }, () => {
      // 保存到本地存储
      saveFoodList(updatedList);
      Taro.showToast({ title: '添加成功', icon: 'success' })
    })
  }

  handleUseFood = (foodId: string) => {
    const { foodList } = this.state
    const updatedList = foodList.map(item => {
      if (item.id === foodId && item.quantity > 0) {
        return { ...item, quantity: item.quantity - 1 }
      }
      return item
    }).filter(item => item.quantity > 0) // 移除数量为0的食材
    
    this.setState({ foodList: updatedList }, () => {
      saveFoodList(updatedList)
      Taro.showToast({ title: '使用成功', icon: 'success' })
    })
  }

  getCurrentDateString = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = now.getMonth() + 1
    const date = now.getDate()
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    const weekday = weekdays[now.getDay()]
    
    return `${year}年${month}月${date}日${weekday}`
  }

  getStatusColor = (status: 'normal' | 'low' | 'expiring') => {
    switch (status) {
      case 'low': return '#FF9800'
      case 'expiring': return '#DC3545'
      default: return '#4CAF50'
    }
  }

  getStatusIcon = (status: 'normal' | 'low' | 'expiring') => {
    switch (status) {
      case 'low': return '⚠️'
      case 'expiring': return '🚨'
      default: return '✅'
    }
  }

  getCategoryIcon = (category: string) => {
    switch (category) {
      case '蔬菜': return '🥬'
      case '主食': return '🍚'
      case '肉类': return '🥩'
      case '水果': return '🍎'
      default: return '🍱'
    }
  }

  handleInputChange = (field: keyof Omit<FoodItem, 'id' | 'purchaseDate' | 'status'>, value: string | number) => {
    this.setState(prev => ({
      newFood: {
        ...prev.newFood,
        [field]: field === 'quantity' ? Number(value) : value
      }
    }))
  }

  onRefresh = () => {
    this.setState({ refreshing: true })
    // 模拟刷新
    setTimeout(() => {
      this.setState({ refreshing: false })
    }, 1000)
  }

  // 处理食材选择
  handleFoodSelect = (food: { name: string; category: string }) => {
    this.setState(prev => ({
      newFood: {
        ...prev.newFood,
        name: food.name,
        category: food.category
      },
      showFoodSelector: false,
      foodSearchValue: ''
    }))
  }

  // 处理分类选择
  handleCategorySelect = (category: string) => {
    this.setState(prev => ({
      newFood: {
        ...prev.newFood,
        category: category
      },
      showCategorySelector: false,
      categorySearchValue: ''
    }))
  }

  // 处理单位选择
  handleUnitSelect = (unit: string) => {
    this.setState(prev => ({
      newFood: {
        ...prev.newFood,
        unit: unit
      },
      showUnitSelector: false
    }))
  }

  // 处理存放位置选择
  handleLocationSelect = (location: string) => {
    this.setState(prev => ({
      newFood: {
        ...prev.newFood,
        location: location
      },
      showLocationSelector: false
    }))
  }

  // 处理日期选择
  handleDateChange = (e: any) => {
    this.setState(prev => ({
      newFood: {
        ...prev.newFood,
        expiryDate: e.detail.value
      }
    }))
  }

  // 获取过滤后的食材列表
  getFilteredFoods = () => {
    const { foodSearchValue } = this.state
    
    // 合并预设食材和自定义食材
    const customFoods = getCustomFoods()
    const allFoods = [...this.presetFoods, ...customFoods]
    
    if (!foodSearchValue) return allFoods
    return allFoods.filter(food => 
      food.name.includes(foodSearchValue) || food.category.includes(foodSearchValue)
    )
  }

  // 获取过滤后的分类列表
  getFilteredCategories = () => {
    const { categorySearchValue } = this.state
    if (!categorySearchValue) return this.presetCategories
    return this.presetCategories.filter(category => 
      category.name.includes(categorySearchValue)
    )
  }

  // 添加新分类
  handleAddNewCategory = () => {
    const { categorySearchValue } = this.state
    if (categorySearchValue.trim()) {
      this.handleCategorySelect(categorySearchValue.trim())
    }
  }

  // 处理分类筛选选择
  handleCategoryFilterSelect = (category: string) => {
    this.setState({
      selectedCategory: category,
      showCategoryFilter: false
    })
  }

  // 处理位置筛选选择
  handleLocationFilterSelect = (location: string) => {
    this.setState({
      selectedLocation: location,
      showLocationFilter: false
    })
  }

  // 处理排序选择
  handleSortSelect = (sortOption: string) => {
    this.setState({
      sortBy: sortOption,
      showSortFilter: false
    })
  }

  // 获取筛选和排序后的食材列表
  getFilteredAndSortedFoodList = () => {
    const { foodList, selectedCategory, selectedLocation, sortBy } = this.state
    
    // 更新食材状态
    const updatedFoodList = foodList.map(item => ({
      ...item,
      status: calculateStatus(item.expiryDate)
    }))

    // 按分类筛选
    let filteredList = selectedCategory === '分类排序' 
      ? updatedFoodList 
      : updatedFoodList.filter(item => item.category === selectedCategory)

    // 按位置筛选
    filteredList = selectedLocation === '位置排序' 
      ? filteredList 
      : filteredList.filter(item => item.location === selectedLocation)

    // 按排序方式排序
    switch (sortBy) {
      case '按名称排序 A-Z':
        filteredList.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
        break
      case '按名称排序 Z-A':
        filteredList.sort((a, b) => b.name.localeCompare(a.name, 'zh-CN'))
        break
      case '按添加时间 最新':
        filteredList.sort((a, b) => new Date(b.purchaseDate).getTime() - new Date(a.purchaseDate).getTime())
        break
      case '按添加时间 最旧':
        filteredList.sort((a, b) => new Date(a.purchaseDate).getTime() - new Date(b.purchaseDate).getTime())
        break
      case '按过期时间 即将过期':
        filteredList.sort((a, b) => new Date(a.expiryDate).getTime() - new Date(b.expiryDate).getTime())
        break
      case '按过期时间 最晚过期':
        filteredList.sort((a, b) => new Date(b.expiryDate).getTime() - new Date(a.expiryDate).getTime())
        break
      case '按数量 最多':
        filteredList.sort((a, b) => b.quantity - a.quantity)
        break
      case '按数量 最少':
        filteredList.sort((a, b) => a.quantity - b.quantity)
        break
      case '按状态排序':
      default:
        // 默认按状态排序：即将过期 > 低库存 > 正常
        filteredList.sort((a, b) => {
          const statusOrder = { 'expiring': 0, 'low': 1, 'normal': 2 } as const
          return statusOrder[a.status] - statusOrder[b.status]
        })
        break
    }

    return filteredList
  }

  // 获取分类筛选选项
  getCategoryFilterOptions = () => {
    return [
      { name: '分类排序', emoji: '📋' },
      ...this.presetCategories
    ]
  }

  // 获取位置筛选选项
  getLocationFilterOptions = () => {
    return [
      { name: '位置排序', emoji: '📋' },
      ...this.presetLocations
    ]
  }

  // 获取排序选项
  getSortOptions = () => {
    return [
      { name: '按状态排序', description: '即将过期优先' },
      { name: '按名称排序 A-Z', description: '名称升序' },
      { name: '按名称排序 Z-A', description: '名称降序' },
      { name: '按添加时间 最新', description: '最新添加优先' },
      { name: '按添加时间 最旧', description: '最早添加优先' },
      { name: '按过期时间 即将过期', description: '即将过期优先' },
      { name: '按过期时间 最晚过期', description: '最晚过期优先' },
      { name: '按数量 最多', description: '数量多的优先' },
      { name: '按数量 最少', description: '数量少的优先' }
    ]
  }

  // 处理预警图标点击
  handleWarningClick = () => {
    Taro.navigateTo({
      url: '/pages/expiry-warning/index'
    })
  }

  // 处理统计页面点击
  handleStatisticsClick = () => {
    Taro.navigateTo({
      url: '/pages/statistics/index'
    })
  }

  // 处理导出食材数据
  handleExportData = async () => {
    try {
      await exportFoodData()
    } catch (error) {
      console.error('导出失败:', error)
    }
  }

  // 处理导入食材数据
  handleImportData = async () => {
    try {
      const success = await importFoodData()
      if (success) {
        // 导入成功后重新加载数据
        const updatedFoodList = getFoodList()
        this.setState({ foodList: updatedFoodList })
      }
    } catch (error) {
      console.error('导入失败:', error)
    }
  }

  // 处理搜索功能
  handleSearchClick = () => {
    this.setState({ showSearchModal: true })
  }

  // 处理搜索查询变化
  handleSearchQueryChange = (value: string) => {
    this.setState({ searchQuery: value })
    this.performSearch(value)
  }

  // 执行搜索
  performSearch = (query: string) => {
    const { foodList } = this.state
    
    if (!query.trim()) {
      this.setState({ searchResults: [] })
      return
    }

    // 更新食材状态
    const updatedFoodList = foodList.map(item => ({
      ...item,
      status: calculateStatus(item.expiryDate)
    }))

    // 搜索逻辑：支持按名称、分类、位置、状态搜索
    const results = updatedFoodList.filter(item => {
      const searchTerm = query.toLowerCase().trim()
      
      // 按名称搜索
      if (item.name.toLowerCase().includes(searchTerm)) return true
      
      // 按分类搜索
      if (item.category.toLowerCase().includes(searchTerm)) return true
      
      // 按位置搜索
      if (item.location && item.location.toLowerCase().includes(searchTerm)) return true
      
      // 按状态搜索
      const statusMap = {
        'normal': ['正常', '新鲜', '良好'],
        'low': ['低库存', '不足', '少'],
        'expiring': ['即将过期', '过期', '快过期', '临期']
      }
      
      const statusKeywords = statusMap[item.status] || []
      if (statusKeywords.some(keyword => keyword.includes(searchTerm))) return true
      
      // 按单位搜索
      if (item.unit && item.unit.toLowerCase().includes(searchTerm)) return true
      
      return false
    })

    // 按相关性排序：名称匹配优先，然后是分类匹配
    results.sort((a, b) => {
      const searchTerm = query.toLowerCase().trim()
      
      // 名称完全匹配优先
      if (a.name.toLowerCase() === searchTerm && b.name.toLowerCase() !== searchTerm) return -1
      if (b.name.toLowerCase() === searchTerm && a.name.toLowerCase() !== searchTerm) return 1
      
      // 名称开头匹配优先
      if (a.name.toLowerCase().startsWith(searchTerm) && !b.name.toLowerCase().startsWith(searchTerm)) return -1
      if (b.name.toLowerCase().startsWith(searchTerm) && !a.name.toLowerCase().startsWith(searchTerm)) return 1
      
      // 按状态排序：即将过期 > 低库存 > 正常
      const statusOrder = { 'expiring': 0, 'low': 1, 'normal': 2 } as const
      return statusOrder[a.status] - statusOrder[b.status]
    })

    this.setState({ searchResults: results })
  }

  // 关闭搜索模态框
  handleCloseSearchModal = () => {
    this.setState({ 
      showSearchModal: false, 
      searchQuery: '', 
      searchResults: [] 
    })
  }

  // 从搜索结果选择食材
  handleSelectSearchResult = (item: FoodItem) => {
    // 关闭搜索模态框
    this.handleCloseSearchModal()
    
    // 可以添加额外的逻辑，比如高亮显示选中的食材
    Taro.showToast({ 
      title: `已选择 ${item.name}`, 
      icon: 'success',
      duration: 1500
    })
  }

  // 处理总食材卡片点击
  handleTotalIngredientsClick = () => {
    this.setState({ showTotalIngredientsModal: true })
  }

  // 关闭总食材模态框
  handleCloseTotalIngredientsModal = () => {
    this.setState({ showTotalIngredientsModal: false })
  }

  // 处理需关注卡片点击
  handleAttentionClick = () => {
    this.setState({ showAttentionModal: true })
  }

  // 关闭需关注模态框
  handleCloseAttentionModal = () => {
    this.setState({ showAttentionModal: false })
  }

  // 获取需要关注的食材列表 - 只关注低库存食材
  getAttentionItems = () => {
    const { foodList } = this.state
    
    // 筛选出低库存的食材（数量少于等于2的食材）
    const attentionItems = foodList
      .filter(item => item.quantity <= 2)
      .sort((a, b) => {
        // 按数量排序：数量最少的优先
        return a.quantity - b.quantity
      })

    return attentionItems
  }

  // 处理食材卡片点击 - 打开编辑模态框
  handleFoodCardClick = (item: FoodItem) => {
    this.setState({
      showEditModal: true,
      editingFood: item,
      editFood: { ...item },
      editFoodSearchValue: '',
      editCategorySearchValue: ''
    })
  }

  // 关闭编辑模态框
  handleCloseEditModal = () => {
    this.setState({
      showEditModal: false,
      editingFood: null,
      editFood: {},
      showEditFoodSelector: false,
      showEditCategorySelector: false,
      showEditUnitSelector: false,
      showEditLocationSelector: false,
      editFoodSearchValue: '',
      editCategorySearchValue: ''
    })
  }

  // 保存编辑后的食材
  handleSaveEditFood = () => {
    const { editingFood, editFood, foodList } = this.state
    
    if (!editingFood || !editFood.name || !editFood.quantity) {
      Taro.showToast({ title: '请填写食材名称和数量', icon: 'none' })
      return
    }

    // 更新食材信息
    const success = updateFood(editingFood.id, editFood)
    
    if (success) {
      // 重新加载食材列表
      const updatedFoodList = getFoodList()
      this.setState({
        foodList: updatedFoodList,
        showEditModal: false,
        editingFood: null,
        editFood: {}
      })
      
      Taro.showToast({ title: '修改成功', icon: 'success' })
    } else {
      Taro.showToast({ title: '修改失败', icon: 'error' })
    }
  }

  // 处理编辑表单输入变化
  handleEditInputChange = (field: keyof FoodItem, value: string | number) => {
    this.setState(prev => ({
      editFood: {
        ...prev.editFood,
        [field]: field === 'quantity' ? Number(value) : value
      }
    }))
  }

  // 删除食材
  handleDeleteFood = async (foodId: string, foodName: string) => {
    try {
      const res = await Taro.showModal({
        title: '确认删除',
        content: `确定要删除食材"${foodName}"吗？此操作不可撤销。`,
        confirmText: '删除',
        cancelText: '取消'
      })

      if (res.confirm) {
        const success = deleteFood(foodId)
        
        if (success) {
          // 重新加载食材列表
          const updatedFoodList = getFoodList()
          this.setState({ foodList: updatedFoodList })
          
          Taro.showToast({ title: '删除成功', icon: 'success' })
        } else {
          Taro.showToast({ title: '删除失败', icon: 'error' })
        }
      }
    } catch (error) {
      console.error('删除食材失败:', error)
      Taro.showToast({ title: '删除失败', icon: 'error' })
    }
  }

  // 从编辑模态框删除食材
  handleDeleteFromEdit = async () => {
    const { editingFood } = this.state
    
    if (!editingFood) return

    try {
      const res = await Taro.showModal({
        title: '确认删除',
        content: `确定要删除食材"${editingFood.name}"吗？此操作不可撤销。`,
        confirmText: '删除',
        cancelText: '取消'
      })

      if (res.confirm) {
        const success = deleteFood(editingFood.id)
        
        if (success) {
          // 重新加载食材列表
          const updatedFoodList = getFoodList()
          this.setState({
            foodList: updatedFoodList,
            showEditModal: false,
            editingFood: null,
            editFood: {}
          })
          
          Taro.showToast({ title: '删除成功', icon: 'success' })
        } else {
          Taro.showToast({ title: '删除失败', icon: 'error' })
        }
      }
    } catch (error) {
      console.error('删除食材失败:', error)
      Taro.showToast({ title: '删除失败', icon: 'error' })
    }
  }

  // 编辑模态框的选择器处理方法
  handleEditFoodSelect = (food: { name: string; category: string }) => {
    this.setState(prev => ({
      editFood: {
        ...prev.editFood,
        name: food.name,
        category: food.category
      },
      showEditFoodSelector: false,
      editFoodSearchValue: ''
    }))
  }

  handleEditCategorySelect = (category: string) => {
    this.setState(prev => ({
      editFood: {
        ...prev.editFood,
        category: category
      },
      showEditCategorySelector: false,
      editCategorySearchValue: ''
    }))
  }

  handleEditUnitSelect = (unit: string) => {
    this.setState(prev => ({
      editFood: {
        ...prev.editFood,
        unit: unit
      },
      showEditUnitSelector: false
    }))
  }

  handleEditLocationSelect = (location: string) => {
    this.setState(prev => ({
      editFood: {
        ...prev.editFood,
        location: location
      },
      showEditLocationSelector: false
    }))
  }

  handleEditDateChange = (e: any) => {
    this.setState(prev => ({
      editFood: {
        ...prev.editFood,
        expiryDate: e.detail.value
      }
    }))
  }

  // 获取编辑模态框过滤后的食材列表
  getEditFilteredFoods = () => {
    const { editFoodSearchValue } = this.state
    if (!editFoodSearchValue) return this.presetFoods
    return this.presetFoods.filter(food => 
      food.name.includes(editFoodSearchValue) || food.category.includes(editFoodSearchValue)
    )
  }

  // 获取编辑模态框过滤后的分类列表
  getEditFilteredCategories = () => {
    const { editCategorySearchValue } = this.state
    if (!editCategorySearchValue) return this.presetCategories
    return this.presetCategories.filter(category => 
      category.name.includes(editCategorySearchValue)
    )
  }

  // 编辑模态框添加新分类
  handleEditAddNewCategory = () => {
    const { editCategorySearchValue } = this.state
    if (editCategorySearchValue.trim()) {
      this.handleEditCategorySelect(editCategorySearchValue.trim())
    }
  }

  // 处理删除全部食材
  handleDeleteAllFood = async () => {
    const { foodList } = this.state
    
    if (foodList.length === 0) {
      Taro.showToast({ 
        title: '暂无食材可删除', 
        icon: 'none',
        duration: 2000
      })
      return
    }

    try {
      const res = await Taro.showModal({
        title: '确认删除全部',
        content: `确定要删除所有 ${foodList.length} 种食材吗？此操作不可撤销。`,
        confirmText: '全部删除',
        cancelText: '取消'
      })

      if (res.confirm) {
        const success = deleteAllFood()
        
        if (success) {
          // 更新状态
          this.setState({ foodList: [] })
          
          Taro.showToast({ 
            title: '已删除所有食材', 
            icon: 'success',
            duration: 2000
          })
        } else {
          Taro.showToast({ 
            title: '删除失败，请重试', 
            icon: 'error',
            duration: 2000
          })
        }
      }
    } catch (error) {
      console.error('删除所有食材失败:', error)
      Taro.showToast({ 
        title: '删除失败，请重试', 
        icon: 'error',
        duration: 2000
      })
    }
  }

  
  render() {
    const { 
      foodList, 
      showAddModal, 
      newFood, 
      refreshing,
      showFoodSelector,
      showCategorySelector,
      showUnitSelector,
      foodSearchValue,
      categorySearchValue,
      selectedCategory,
      sortBy,
      showCategoryFilter,
      showSortFilter
    } = this.state
    
    // 使用新的筛选和排序逻辑
    const filteredAndSortedFoodList = this.getFilteredAndSortedFoodList()

    // 计算统计数据（基于原始数据，不受筛选影响）
    const totalItems = foodList.length
    const expiringItems = foodList.filter(item => calculateStatus(item.expiryDate) === 'expiring').length
    const lowStockItems = foodList.filter(item => calculateStatus(item.expiryDate) === 'low').length
    
    // 计算消耗趋势 - 基于低库存和即将过期的食材比例
    const consumptionTrend = totalItems > 0 ? Math.round(((expiringItems + lowStockItems) / totalItems) * 100) : 0

    return (
      <View className='kitchen-page'>
        {/* 顶部导航栏 */}
        <View className='top-navbar'>
          <View className='navbar-left'>
            <Text className='app-title'>厨房助手</Text>
          </View>
          <View className='navbar-right'>
            <AtIcon 
              value='help' 
              size='20' 
              className='nav-icon help-icon' 
              onClick={this.handleShowUserGuide}
            />
            <AtBadge value={expiringItems} maxValue={99}>
              <AtIcon 
                value='bell' 
                size='20' 
                className='nav-icon' 
                onClick={this.handleWarningClick}
              />
            </AtBadge>
            <View className='user-avatar'>
              <Text className='avatar-text'>厨</Text>
            </View>
          </View>
        </View>

        {/* 用户指南卡片 */}
        {this.state.showUserGuide && (
          <View className='user-guide-overlay'>
            <View className={`user-guide-card ${this.state.userGuideClosing ? 'closing' : ''}`}>
              <View className='guide-header'>
                <Text className='guide-title'>🎉 欢迎使用厨房助手！</Text>
                <View 
                  className='guide-close-btn'
                  onClick={this.handleCloseUserGuide}
                >
                  <AtIcon value='close' size='20' className='close-icon' />
                </View>
              </View>
              
              <View className='guide-content'>
                <View className='guide-section'>
                  <Text className='guide-section-title'>📱 快速上手</Text>
                  <Text className='guide-item'>• 点击"添加食材"按钮开始管理您的食材</Text>
                  <Text className='guide-item'>• 支持搜索和选择预设食材，也可以添加自定义食材,已经添加过的新食材无需重新添加</Text>
                  <Text className='guide-item'>• 设置过期时间，系统会自动提醒您</Text>
                </View>
                
                <View className='guide-section'>
                  <Text className='guide-section-title'>🔍 智能功能</Text>
                  <Text className='guide-item'>• 使用搜索功能快速找到食材</Text>
                  <Text className='guide-item'>• 按分类、位置、状态等方式筛选和排序</Text>
                  <Text className='guide-item'>• 点击统计卡片查看详细信息</Text>
                </View>
                
                <View className='guide-section'>
                  <Text className='guide-section-title'>💾 数据管理</Text>
                  <Text className='guide-item'>• 使用"一键导出"备份您的食材数据</Text>
                  <Text className='guide-item'>• 使用"一键导入"恢复或同步数据</Text>
                  <Text className='guide-item'>• 所有数据安全存储在本地</Text>
                </View>

                <View className='guide-section'>
                  <Text className='guide-section-title'>📋 可视化面板</Text>
                  <Text className='guide-item'>• 一键可视化您的食材种类分布, 食材健康状况</Text>
                </View>
                
                <View className='guide-footer'>
                  <Text className='guide-footer-text'>点击右上角 ✕ 关闭此指南，开始使用吧！</Text>
                </View>
              </View>
            </View>
          </View>
        )}

        {/* 欢迎信息 */}
        <View className='welcome-section'>
          <Text className='welcome-text'>你好，厨师长！</Text>
          <Text className='date-text'>
            今天是 {this.getCurrentDateString()}，你有 <Text className='highlight'>{expiringItems} 种食材</Text> 即将过期
          </Text>
        </View>

        {/* 统计卡片 */}
        <View className='stats-section'>
          <View className='stat-card total' onClick={this.handleTotalIngredientsClick}>
            <View className='stat-icon'>🛒</View>
            <View className='stat-info'>
              <Text className='stat-label'>总食材</Text>
              <Text className='stat-value'>{totalItems}</Text>
              <Text className='stat-trend'>{totalItems === 0 ? '暂无食材' : `共 ${totalItems} 种食材`}</Text>
            </View>
          </View>
          
          <View className='stat-card expiring'>
            <View className='stat-icon'>⚠️</View>
            <View className='stat-info'>
              <Text className='stat-label'>即将过期</Text>
              <Text className='stat-value'>{expiringItems}</Text>
              <Text className='stat-trend'>{expiringItems === 0 ? '暂无过期食材' : '需要尽快使用'}</Text>
            </View>
          </View>
          
          <View className='stat-card consumption' onClick={this.handleAttentionClick}>
            <View className='stat-icon'>📈</View>
            <View className='stat-info'>
              <Text className='stat-label'>需关注</Text>
              <Text className='stat-value'>{this.getAttentionItems().length}</Text>
              <Text className='stat-trend'>{this.getAttentionItems().length === 0 ? '食材状态良好' : '需要关注的食材'}</Text>
            </View>
          </View>
        </View>


        {/* 食材库存标题 */}
        <View className='inventory-header'>
          <View className='inventory-title-section'>
            <Text className='inventory-title'>食材库存</Text>
            <AtButton 
              type='primary'
              size='small'
              onClick={this.handleSearchClick}
              className='search-button'
            >
              <AtIcon value='search' size='18' className='search-icon' />
              搜索
            </AtButton>
          </View>
          <View className='filter-controls'>
            <View 
              className='filter-item'
              onClick={() => this.setState({ showCategoryFilter: true })}
            >
              <Text className='filter-text'>{selectedCategory}</Text>
              <AtIcon value='chevron-down' size='14' />
            </View>
            <View 
              className='filter-item'
              onClick={() => this.setState({ showLocationFilter: true })}
            >
              <Text className='filter-text'>{this.state.selectedLocation}</Text>
              <AtIcon value='chevron-down' size='14' />
            </View>
            <View 
              className='filter-item'
              onClick={() => this.setState({ showSortFilter: true })}
            >
              <Text className='filter-text'>{sortBy}</Text>
              <AtIcon value='chevron-down' size='14' />
            </View>
          </View>
        </View>

        {/* 食材列表 */}
        <ScrollView className='food-list-container' 
          onPullDownRefresh={this.onRefresh} 
          refreshing={refreshing} 
          scrollY
          {...{} as CustomScrollViewProps}
        >
          <View className='food-grid'>
            {filteredAndSortedFoodList.map(item => (
              <View key={item.id} className={`food-card ${item.status}`}>
                {/* 删除按钮 - 右上角 */}
                <View 
                  className='delete-button-corner'
                  onClick={(e) => {
                    e.stopPropagation()
                    this.handleDeleteFood(item.id, item.name)
                  }}
                >
                  <AtIcon value='close' size='16' className='delete-icon' />
                </View>

                {/* 状态标签 */}
                {item.status !== 'normal' && (
                  <View className={`status-tag ${item.status}`}>
                    <Text className='status-text'>
                      {item.status === 'expiring' ? '即将过期' : '低库存'}
                    </Text>
                  </View>
                )}
                
                {/* 可点击的卡片内容区域 */}
                <View 
                  className='food-card-content'
                  onClick={() => this.handleFoodCardClick(item)}
                >
                  {/* 食材图片 */}
                  <View className='food-image-container'>
                    <View className='food-image-placeholder'>
                      <Text className='food-emoji'>{this.getCategoryIcon(item.category)}</Text>
                      <Text className='food-placeholder-text'>{item.name}</Text>
                    </View>
                  </View>
                  
                  {/* 食材信息 */}
                  <View className='food-info'>
                    <Text className='food-name'>{item.name}</Text>
                    <View className='food-meta'>
                      <View className='meta-item'>
                        <Text className='meta-icon'>{this.getCategoryIcon(item.category)}</Text>
                        <Text className='meta-text'>{item.category}</Text>
                      </View>
                      {item.location && (
                        <View className='meta-item'>
                          <Text className='meta-icon'>{item.location === '冷冻' ? '🧊' : '❄️'}</Text>
                          <Text className='meta-text'>{item.location}</Text>
                        </View>
                      )}
                      {item.expiryDate && (
                        <View className='meta-item'>
                          <Text className='meta-text'>{item.expiryDate.split('-').slice(1).join('月')}</Text>
                        </View>
                      )}
                    </View>
                    
                    {/* 剩余量进度条 */}
                    <View className='quantity-section'>
                      <Text className='quantity-label'>剩余量</Text>
                      <View className='quantity-bar'>
                        <View 
                          className={`quantity-fill ${item.status}`}
                          style={{ 
                            width: item.status === 'low' ? '25%' : 
                                   item.status === 'expiring' ? '60%' : '80%' 
                          }}
                        />
                      </View>
                      <Text className='quantity-text'>{item.quantity} {item.unit}</Text>
                    </View>
                  </View>
                </View>
                
                {/* 操作按钮区域 */}
                <View className='food-actions'>
                  <AtButton 
                    type='primary'
                    size='small'
                    onClick={(e) => {
                      e.stopPropagation()
                      this.handleUseFood(item.id)
                    }}
                    className='use-food-btn'
                  >
                    使用此食材
                  </AtButton>
                  <AtButton 
                    type='secondary'
                    size='small'
                    onClick={(e) => {
                      e.stopPropagation()
                      this.handleDeleteFood(item.id, item.name)
                    }}
                    className='delete-food-btn'
                  >
                    <AtIcon value='trash' size='18' className='delete-btn-icon' />
                    删除
                  </AtButton>
                </View>
              </View>
            ))}
            
          </View>
        </ScrollView>

        {/* 底部操作按钮 */}
        <View className='bottom-actions'>
          <AtButton 
            type='secondary'
            size='normal'
            onClick={this.handleExportData}
            className='action-button export-btn circular-btn'
          >
            <AtIcon value='download' size='18' className='button-icon' />
            一键导出
          </AtButton>
          
          {/* 统计按钮 - 添加食材左侧 */}
          <AtButton 
            type='secondary'
            size='normal'
            onClick={this.handleStatisticsClick}
            className='action-button statistics-btn circular-btn'
          >
            <AtIcon value='analytics' size='18' className='button-icon' />
            统计
          </AtButton>
          
          {/* 中间的添加食材按钮 - 圆形 */}
          <AtButton 
            type='primary'
            size='normal'
            onClick={this.handleAddFood}
            className='action-button add-food-btn-bottom circular-btn main-add-btn'
          >
            <AtIcon value='add' size='24' className='button-icon' />
            添加食材
          </AtButton>
          
          <AtButton 
            type='secondary'
            size='normal'
            onClick={this.handleImportData}
            className='action-button import-btn circular-btn'
          >
            <AtIcon value='upload' size='18' className='button-icon' />
            一键导入
          </AtButton>
          <AtButton 
            type='secondary'
            size='normal'
            onClick={this.handleDeleteAllFood}
            className='action-button delete-all-btn circular-btn'
          >
            <AtIcon value='trash' size='18' className='button-icon' />
            删除全部
          </AtButton>
        </View>

        {/* 添加食材浮层 */}
        <AtFloatLayout 
          isOpened={showAddModal} 
          title='添加新食材'
          onClose={this.handleCloseModal}
          className='add-food-modal'
        >
          <View className='add-form'>
            {/* 食材名称输入/选择 */}
            <View className='form-field'>
              <Text className='field-label required'>食材名称 *</Text>
              <View className='input-with-selector'>
                <Input
                  className='native-input required-field'
                  type='text'
                  value={newFood.name || ''}
                  onInput={(e) => this.handleInputChange('name', e.detail.value)}
                  onFocus={() => this.setState({ nameInputFocused: true })}
                  onBlur={() => this.setState({ nameInputFocused: false })}
                />
                <View 
                  className='selector-button' 
                  onClick={() => {
                    console.log('点击食材选择器')
                    this.setState({ showFoodSelector: true })
                  }}
                >
                  <Text className='selector-button-text'>选择</Text>
                </View>
              </View>
            </View>
            
            {/* 分类选择 */}
            <View className='form-field'>
              <Text className='field-label'>选择分类</Text>
              <View 
                className='selector-field ios-style' 
                onClick={() => {
                  console.log('点击分类选择器')
                  this.setState({ showCategorySelector: true })
                }}
              >
                <Text className={`selector-text ios-style ${newFood.category ? 'selected' : ''}`}>
                  {newFood.category}
                </Text>
                <Text className='chevron-icon'>▼</Text>
              </View>
            </View>
            
            {/* 数量输入 */}
            <View className='form-field'>
              <Text className='field-label required'>数量 *</Text>
              <Input
                className='native-input required-field'
                type='number'
                value={newFood.quantity?.toString() || ''}
                onInput={(e) => this.handleInputChange('quantity', Number(e.detail.value))}
                onFocus={() => this.setState({ quantityInputFocused: true })}
                onBlur={() => this.setState({ quantityInputFocused: false })}
              />
            </View>
            
            {/* 单位选择 */}
            <View className='form-field'>
              <Text className='field-label'>单位</Text>
              <View 
                className='selector-field ios-style' 
                onClick={() => {
                  console.log('点击单位选择器')
                  this.setState({ showUnitSelector: true })
                }}
              >
                <Text className={`selector-text ios-style ${newFood.unit ? 'selected' : ''}`}>
                  {newFood.unit}
                </Text>
                <Text className='chevron-icon'>▼</Text>
              </View>
            </View>
            
            {/* 存放位置选择 */}
            <View className='form-field'>
              <Text className='field-label'>存放位置</Text>
              <View 
                className='selector-field ios-style' 
                onClick={() => {
                  console.log('点击位置选择器')
                  this.setState({ showLocationSelector: true })
                }}
              >
                <Text className={`selector-text ios-style ${newFood.location ? 'selected' : ''}`}>
                  {newFood.location}
                </Text>
                <Text className='chevron-icon'>▼</Text>
              </View>
            </View>
            
            {/* 过期日期选择 */}
            <View className='form-field'>
              <Text className='field-label'>过期时间</Text>
              <Picker
                mode='date'
                value={newFood.expiryDate || ''}
                onChange={this.handleDateChange}
              >
                <View className='selector-field ios-style'>
                  <Text className={`selector-text ios-style ${newFood.expiryDate ? 'selected' : ''}`}>
                    {newFood.expiryDate}
                  </Text>
                  <Text className='chevron-icon'>📅</Text>
                </View>
              </Picker>
            </View>
            
            <View className='form-actions'>
              <AtButton onClick={this.handleCloseModal} className='form-button cancel'>取消</AtButton>
              <AtButton type='primary' onClick={this.handleSaveFood} className='form-button confirm'>确认添加</AtButton>
            </View>
          </View>
        </AtFloatLayout>

        {/* 食材选择器 */}
        <AtFloatLayout 
          isOpened={showFoodSelector} 
          title='选择食材'
          onClose={() => this.setState({ showFoodSelector: false, foodSearchValue: '' })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <AtSearchBar
              value={foodSearchValue}
              placeholder='搜索食材名称'
              onChange={(value) => this.setState({ foodSearchValue: value })}
              onActionClick={() => {
                if (foodSearchValue.trim()) {
                  this.handleFoodSelect({ name: foodSearchValue.trim(), category: '其他' })
                }
              }}
              actionName='添加'
            />
            <ScrollView className='options-list' scrollY>
              {this.getFilteredFoods().map((food, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleFoodSelect(food)}
                >
                  <Text className='option-emoji'>{food.emoji}</Text>
                  <View className='option-info'>
                    <Text className='option-name'>{food.name}</Text>
                    <Text className='option-category'>{food.category}</Text>
                  </View>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 分类选择器 */}
        <AtFloatLayout 
          isOpened={showCategorySelector} 
          title='选择分类'
          onClose={() => this.setState({ showCategorySelector: false, categorySearchValue: '' })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <AtSearchBar
              value={categorySearchValue}
              placeholder='搜索或新建分类'
              onChange={(value) => this.setState({ categorySearchValue: value })}
              onActionClick={this.handleAddNewCategory}
              actionName='新建'
            />
            <ScrollView className='options-list' scrollY>
              {this.getFilteredCategories().map((category, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleCategorySelect(category.name)}
                >
                  <Text className='option-emoji'>{category.emoji}</Text>
                  <Text className='option-name'>{category.name}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 单位选择器 */}
        <AtFloatLayout 
          isOpened={showUnitSelector} 
          title='选择单位'
          onClose={() => this.setState({ showUnitSelector: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.presetUnits.map((unit, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleUnitSelect(unit)}
                >
                  <Text className='option-name'>{unit}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 存放位置选择器 */}
        <AtFloatLayout 
          isOpened={this.state.showLocationSelector} 
          title='选择存放位置'
          onClose={() => this.setState({ showLocationSelector: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.presetLocations.map((location, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleLocationSelect(location.name)}
                >
                  <Text className='option-emoji'>{location.emoji}</Text>
                  <Text className='option-name'>{location.name}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 分类筛选选择器 */}
        <AtFloatLayout 
          isOpened={showCategoryFilter} 
          title='选择分类筛选'
          onClose={() => this.setState({ showCategoryFilter: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.getCategoryFilterOptions().map((category, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleCategoryFilterSelect(category.name)}
                >
                  <Text className='option-emoji'>{category.emoji}</Text>
                  <Text className='option-name'>{category.name}</Text>
                  {selectedCategory === category.name && (
                    <AtIcon value='check' size='16' color='#6366f1' />
                  )}
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 位置筛选选择器 */}
        <AtFloatLayout 
          isOpened={this.state.showLocationFilter} 
          title='选择位置筛选'
          onClose={() => this.setState({ showLocationFilter: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.getLocationFilterOptions().map((location, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleLocationFilterSelect(location.name)}
                >
                  <Text className='option-emoji'>{location.emoji}</Text>
                  <Text className='option-name'>{location.name}</Text>
                  {this.state.selectedLocation === location.name && (
                    <AtIcon value='check' size='16' color='#6366f1' />
                  )}
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 排序选择器 */}
        <AtFloatLayout 
          isOpened={showSortFilter} 
          title='选择排序方式'
          onClose={() => this.setState({ showSortFilter: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.getSortOptions().map((sortOption, index) => (
                <View 
                  key={index} 
                  className='option-item sort-option'
                  onClick={() => this.handleSortSelect(sortOption.name)}
                >
                  <View className='option-info'>
                    <Text className='option-name'>{sortOption.name}</Text>
                    <Text className='option-category'>{sortOption.description}</Text>
                  </View>
                  {sortBy === sortOption.name && (
                    <AtIcon value='check' size='16' color='#6366f1' />
                  )}
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 搜索模态框 */}
        <AtFloatLayout 
          isOpened={this.state.showSearchModal} 
          title='搜索食材'
          onClose={this.handleCloseSearchModal}
          className='selector-modal'
        >
          <View className='selector-content'>
            <AtSearchBar
              value={this.state.searchQuery}
              placeholder='搜索食材名称、分类、位置或状态'
              onChange={this.handleSearchQueryChange}
              onClear={() => this.setState({ searchQuery: '', searchResults: [] })}
              showActionButton={false}
            />
            <ScrollView className='options-list' scrollY>
              {this.state.searchResults.length > 0 ? (
                this.state.searchResults.map((item) => (
                  <View 
                    key={item.id} 
                    className='option-item'
                    onClick={() => this.handleSelectSearchResult(item)}
                  >
                    <Text className='option-emoji'>{this.getCategoryIcon(item.category)}</Text>
                    <View className='option-info'>
                      <Text className='option-name'>{item.name}</Text>
                      <Text className='option-category'>
                        {item.category} • {item.quantity} {item.unit} • {item.location || '未设置位置'}
                        {item.status === 'expiring' && ' • 即将过期'}
                        {item.status === 'low' && ' • 低库存'}
                      </Text>
                    </View>
                    <View className={`status-indicator ${item.status}`}>
                      <Text className='status-icon'>{this.getStatusIcon(item.status)}</Text>
                    </View>
                  </View>
                ))
              ) : this.state.searchQuery.trim() ? (
                <View className='no-results'>
                  <Text className='no-results-text'>未找到匹配的食材</Text>
                  <Text className='no-results-hint'>
                    尝试搜索食材名称、分类、位置或状态关键词
                  </Text>
                </View>
              ) : (
                <View className='search-tips'>
                  <Text className='tips-title'>搜索提示</Text>
                  <Text className='tips-item'>• 按名称搜索：如"苹果"、"牛奶"</Text>
                  <Text className='tips-item'>• 按分类搜索：如"水果"、"蔬菜"</Text>
                  <Text className='tips-item'>• 按位置搜索：如"冷藏"、"冷冻"</Text>
                  <Text className='tips-item'>• 按状态搜索：如"过期"、"低库存"</Text>
                </View>
              )}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 总食材模态框 */}
        <AtFloatLayout 
          isOpened={this.state.showTotalIngredientsModal} 
          title='总食材列表'
          onClose={this.handleCloseTotalIngredientsModal}
          className='selector-modal'
        >
          <View className='selector-content'>
            <View className='total-ingredients-header'>
              <Text className='total-count'>共 {totalItems} 种食材</Text>
            </View>
            <ScrollView className='options-list' scrollY>
              {foodList.length > 0 ? (
                foodList.map((item, index) => (
                  <View 
                    key={item.id} 
                    className='option-item ingredient-item'
                  >
                    <Text className='option-emoji'>{this.getCategoryIcon(item.category)}</Text>
                    <View className='option-info'>
                      <Text className='option-name'>{item.name}</Text>
                      <Text className='option-category'>
                        {item.category} • {item.quantity} {item.unit}
                        {item.location && ` • ${item.location}`}
                      </Text>
                    </View>
                    <View className={`status-indicator ${calculateStatus(item.expiryDate)}`}>
                      <Text className='status-icon'>{this.getStatusIcon(calculateStatus(item.expiryDate))}</Text>
                    </View>
                  </View>
                ))
              ) : (
                <View className='no-results'>
                  <Text className='no-results-text'>暂无食材</Text>
                  <Text className='no-results-hint'>
                    点击"添加食材"按钮开始添加您的第一个食材
                  </Text>
                </View>
              )}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 需关注食材模态框 */}
        <AtFloatLayout 
          isOpened={this.state.showAttentionModal} 
          title='需关注食材'
          onClose={this.handleCloseAttentionModal}
          className='selector-modal'
        >
          <View className='selector-content'>
            <View className='total-ingredients-header'>
              <Text className='total-count'>{this.getAttentionItems().length}</Text>
              <Text className='total-label'>需要关注</Text>
              <Text className='total-description'>
                {this.getAttentionItems().length === 0 
                  ? '所有食材状态良好，无需特别关注' 
                  : '以下食材需要尽快处理或购买'}
              </Text>
            </View>
            <ScrollView className='options-list' scrollY>
              {this.getAttentionItems().length > 0 ? (
                this.getAttentionItems().map((item) => (
                  <View 
                    key={item.id} 
                    className='option-item ingredient-item'
                    onClick={() => this.handleFoodCardClick(item)}
                  >
                    <Text className='option-emoji'>{this.getCategoryIcon(item.category)}</Text>
                    <View className='option-info'>
                      <Text className='option-name'>{item.name}</Text>
                      <Text className='option-category'>
                        {item.category} • {item.quantity} {item.unit}
                        {item.location && ` • ${item.location}`}
                        • 低库存
                      </Text>
                    </View>
                    <View className={`status-indicator ${item.status}`}>
                      <Text className='status-icon'>{this.getStatusIcon(item.status)}</Text>
                    </View>
                  </View>
                ))
              ) : (
                <View className='no-results'>
                  <Text className='no-results-text'>暂无需关注食材</Text>
                  <Text className='no-results-hint'>
                    所有食材状态良好，继续保持！
                  </Text>
                </View>
              )}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 编辑食材浮层 */}
        <AtFloatLayout 
          isOpened={this.state.showEditModal} 
          title='编辑食材'
          onClose={this.handleCloseEditModal}
          className='add-food-modal'
        >
          <View className='add-form'>
            {/* 食材名称输入/选择 */}
            <View className='form-field'>
              <Text className='field-label required'>食材名称 *</Text>
              <View className='input-with-selector'>
                <Input
                  className='native-input required-field'
                  type='text'
                  value={this.state.editFood.name || ''}
                  onInput={(e) => this.handleEditInputChange('name', e.detail.value)}
                />
                <View 
                  className='selector-button' 
                  onClick={() => this.setState({ showEditFoodSelector: true })}
                >
                  <Text className='selector-button-text'>选择</Text>
                </View>
              </View>
            </View>
            
            {/* 分类选择 */}
            <View className='form-field'>
              <Text className='field-label'>选择分类</Text>
              <View 
                className='selector-field ios-style' 
                onClick={() => this.setState({ showEditCategorySelector: true })}
              >
                <Text className={`selector-text ios-style ${this.state.editFood.category ? 'selected' : ''}`}>
                  {this.state.editFood.category || '请选择分类'}
                </Text>
                <Text className='chevron-icon'>▼</Text>
              </View>
            </View>
            
            {/* 数量输入 */}
            <View className='form-field'>
              <Text className='field-label required'>数量 *</Text>
              <Input
                className='native-input required-field'
                type='number'
                value={this.state.editFood.quantity?.toString() || ''}
                onInput={(e) => this.handleEditInputChange('quantity', Number(e.detail.value))}
              />
            </View>
            
            {/* 单位选择 */}
            <View className='form-field'>
              <Text className='field-label'>单位</Text>
              <View 
                className='selector-field ios-style' 
                onClick={() => this.setState({ showEditUnitSelector: true })}
              >
                <Text className={`selector-text ios-style ${this.state.editFood.unit ? 'selected' : ''}`}>
                  {this.state.editFood.unit || '请选择单位'}
                </Text>
                <Text className='chevron-icon'>▼</Text>
              </View>
            </View>
            
            {/* 存放位置选择 */}
            <View className='form-field'>
              <Text className='field-label'>存放位置</Text>
              <View 
                className='selector-field ios-style' 
                onClick={() => this.setState({ showEditLocationSelector: true })}
              >
                <Text className={`selector-text ios-style ${this.state.editFood.location ? 'selected' : ''}`}>
                  {this.state.editFood.location || '请选择位置'}
                </Text>
                <Text className='chevron-icon'>▼</Text>
              </View>
            </View>
            
            {/* 过期日期选择 */}
            <View className='form-field'>
              <Text className='field-label'>过期时间</Text>
              <Picker
                mode='date'
                value={this.state.editFood.expiryDate || ''}
                onChange={this.handleEditDateChange}
              >
                <View className='selector-field ios-style'>
                  <Text className={`selector-text ios-style ${this.state.editFood.expiryDate ? 'selected' : ''}`}>
                    {this.state.editFood.expiryDate || '请选择日期'}
                  </Text>
                  <Text className='chevron-icon'>📅</Text>
                </View>
              </Picker>
            </View>
            
            <View className='form-actions'>
              <AtButton onClick={this.handleDeleteFromEdit} className='form-button delete-btn'>删除食材</AtButton>
              <AtButton onClick={this.handleCloseEditModal} className='form-button cancel'>取消</AtButton>
              <AtButton type='primary' onClick={this.handleSaveEditFood} className='form-button confirm'>保存修改</AtButton>
            </View>
          </View>
        </AtFloatLayout>

        {/* 编辑模态框 - 食材选择器 */}
        <AtFloatLayout 
          isOpened={this.state.showEditFoodSelector} 
          title='选择食材'
          onClose={() => this.setState({ showEditFoodSelector: false, editFoodSearchValue: '' })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <AtSearchBar
              value={this.state.editFoodSearchValue}
              placeholder='搜索食材名称'
              onChange={(value) => this.setState({ editFoodSearchValue: value })}
              onActionClick={() => {
                if (this.state.editFoodSearchValue.trim()) {
                  this.handleEditFoodSelect({ name: this.state.editFoodSearchValue.trim(), category: '其他' })
                }
              }}
              actionName='添加'
            />
            <ScrollView className='options-list' scrollY>
              {this.getEditFilteredFoods().map((food, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleEditFoodSelect(food)}
                >
                  <Text className='option-emoji'>{food.emoji}</Text>
                  <View className='option-info'>
                    <Text className='option-name'>{food.name}</Text>
                    <Text className='option-category'>{food.category}</Text>
                  </View>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 编辑模态框 - 分类选择器 */}
        <AtFloatLayout 
          isOpened={this.state.showEditCategorySelector} 
          title='选择分类'
          onClose={() => this.setState({ showEditCategorySelector: false, editCategorySearchValue: '' })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <AtSearchBar
              value={this.state.editCategorySearchValue}
              placeholder='搜索或新建分类'
              onChange={(value) => this.setState({ editCategorySearchValue: value })}
              onActionClick={this.handleEditAddNewCategory}
              actionName='新建'
            />
            <ScrollView className='options-list' scrollY>
              {this.getEditFilteredCategories().map((category, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleEditCategorySelect(category.name)}
                >
                  <Text className='option-emoji'>{category.emoji}</Text>
                  <Text className='option-name'>{category.name}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 编辑模态框 - 单位选择器 */}
        <AtFloatLayout 
          isOpened={this.state.showEditUnitSelector} 
          title='选择单位'
          onClose={() => this.setState({ showEditUnitSelector: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.presetUnits.map((unit, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleEditUnitSelect(unit)}
                >
                  <Text className='option-name'>{unit}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>

        {/* 编辑模态框 - 存放位置选择器 */}
        <AtFloatLayout 
          isOpened={this.state.showEditLocationSelector} 
          title='选择存放位置'
          onClose={() => this.setState({ showEditLocationSelector: false })}
          className='selector-modal'
        >
          <View className='selector-content'>
            <ScrollView className='options-list' scrollY>
              {this.presetLocations.map((location, index) => (
                <View 
                  key={index} 
                  className='option-item'
                  onClick={() => this.handleEditLocationSelect(location.name)}
                >
                  <Text className='option-emoji'>{location.emoji}</Text>
                  <Text className='option-name'>{location.name}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        </AtFloatLayout>
      </View>
    )
  }
}
